package com.wswy.wyjk.ui.practice

import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import com.raft.framework.arch.BaseViewModel
import com.wswy.wyjk.model.LicenseType
import com.wswy.wyjk.model.PracticeType
import com.wswy.wyjk.model.SubjectType
import com.wswy.wyjk.model.vo.ExamRegularConfig
import com.wswy.wyjk.ui.practice.exam.ExamCenter
import com.wswy.wyjk.utils.ToastUtils
import com.wswy.wyjk.utils.Tools
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.subscribers.ResourceSubscriber
import timber.log.Timber
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong

class ExamViewModel : BaseViewModel(){

    companion object {
        private val exams = arrayListOf(
            ExamRegularConfig(LicenseType.CAR, SubjectType.KEMU1,45,90),
            ExamRegularConfig(LicenseType.CAR, SubjectType.KEMU4,45,90,2,2,2),
            ExamRegularConfig(LicenseType.TRUCK, SubjectType.KEMU1,45,90),
            ExamRegularConfig(LicenseType.TRUCK, SubjectType.KEMU4,45,90,2,2,2),
            ExamRegularConfig(LicenseType.BUS, SubjectType.KEMU1,45,90,2,2,2),
            ExamRegularConfig(LicenseType.BUS, SubjectType.KEMU4,45,90,2,2,2),
            ExamRegularConfig(LicenseType.MOTO, SubjectType.KEMU1,30,90,2,2,2),
            ExamRegularConfig(LicenseType.MOTO, SubjectType.KEMU4,30,90,2,2,2),
            ExamRegularConfig(LicenseType.KEYUN, SubjectType.CERTIFICATE,60,80,1,1,2),
            ExamRegularConfig(LicenseType.HUOYUN, SubjectType.CERTIFICATE,60,80,1,1,2),
            ExamRegularConfig(LicenseType.JIAOLIAN, SubjectType.CERTIFICATE,60,90),
            ExamRegularConfig(LicenseType.WEIXIAN, SubjectType.CERTIFICATE,90,90),
            ExamRegularConfig(LicenseType.CHUZU, SubjectType.CERTIFICATE,50,40),
            ExamRegularConfig(LicenseType.WANGYUE, SubjectType.CERTIFICATE,50,40)
        )

    }



    //考试状态
    private val examStatusLiveData = MutableLiveData<Boolean>()

    //倒计时
    private val countTimeLiveData = MutableLiveData<String?>()


    private val remainTime =  AtomicLong().apply {
        set(10)
    }

    private var countTimeSubscriber : ResourceSubscriber<Long>? = null

    var examRegularConfig: ExamRegularConfig?=null
    set(value) {
        field = value

        if (value != null){
            remainTime.set(TimeUnit.MINUTES.toSeconds(value.examTime))
            updateRemain(remainTime.get())

            ExamCenter.saveRegularConfig(value)
        }



    }

    /**
     * 开始考试
     */
    fun startExam(){

        if (remainTime.get() == 0L){
            ToastUtils.showText("考试结束")

            return
        }

        examStatusLiveData.postValue(true)

        val subscriber = object : ResourceSubscriber<Long>(){
            override fun onComplete() {
                Timber.e("exam end")
                endExam()
            }

            override fun onNext(t: Long?) {

                t?.let {
                    updateRemain(remainTime.getAndDecrement())
                }
            }

            override fun onError(t: Throwable?) {

            }

        }

        //考试倒计时
        Flowable.intervalRange(0, remainTime.get(), 0, 1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(subscriber)

        addRun(subscriber)

        countTimeSubscriber = subscriber
    }

    /**
     * 停止考试
     */
    fun stopExam(){

        countTimeSubscriber?.dispose()
        countTimeSubscriber = null

        examStatusLiveData.postValue(false)
    }

    fun endExam(){
        ExamCenter.saveExamTime(remainTime.get())



    }


    fun findExamConfig(practiceType: PracticeType) = exams.find { it.carType == practiceType.licenseType && it.subjectType == practiceType.subjectType }

    override fun onCleared() {
        super.onCleared()
        stopExam()
    }

    private fun updateRemain(time:Long){
        //remainTime.set(time)

        countTimeLiveData.postValue("${Tools.formatSecondTime(time)}")
    }

    fun toggleExamStatus(){

        if (examStatusLiveData.value == true){
            //正在考试  停止
            stopExam()
        }else{
            startExam()
        }

    }

    fun getCountTimeLiveData():LiveData<String?> = countTimeLiveData

    fun getExamStatusLiveData():LiveData<Boolean?> = examStatusLiveData
}